#pragma once

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include<sys/types.h>
#include "Log.hpp"

class Socket
{
private: //设置成单例模式
    Socket(int port)
        :_port(port)
        ,_listen_sock(-1)
    {}
    Socket(const Socket &s) = delete;
    Socket* operator=(const Socket&) = delete;
public:
    static Socket *getinstance(int port) //获取单例模式
    {
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        if(nullptr == svr)
        {
            pthread_mutex_lock(&lock);
            if(nullptr == svr)
            {
                svr = new Socket(port);
                svr->InitServer();
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }
    void InitServer()
    {
        GetSocket();
        Bind();
        Listen();
        LOG(INFO, "tcp_server init ... success");
    }
    void GetSocket()
    {
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listen_sock < 0)
        {
            LOG(FATAL, "socket error!");
            exit(1);
        }
        int opt = 1;
        setsockopt(_listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); //使支持地址复用
        LOG(INFO, "create socket ... success");
    }
    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(_listen_sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error!");
            exit(2);
        }
        LOG(INFO, "bind socket ... success");
    }
    void Listen()
    {
        if(listen(_listen_sock, 10) < 0)
        {
            LOG(FATAL, "listen socket error!");
            exit(3);
        }
        LOG(INFO, "listen socket ... success");
    }
    int Sock() { return _listen_sock; }

    ~Socket() 
    {
        if(_listen_sock >= 0) 
            close(_listen_sock);
    }
private:
    int _port;
    int _listen_sock;
    static Socket* svr;
};

Socket* Socket::svr = nullptr; //创建唯一对象，单例模式